package com.example.serviceproviderb.controller;

import com.example.serviceproviderb.model.Product;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/products")
public class ProductController {

    private final Map<Long, Product> products = new ConcurrentHashMap<>();
    private final AtomicLong counter = new AtomicLong();

    @Autowired // 已添加，用于环境注入
    private Environment environment; // 已添加

    private String getInstancePortInfo() { // 已添加辅助方法
        return " [Provider B instance on port: " + environment.getProperty("local.server.port") + "]";
    }

    @PostConstruct
    public void init() {
        // 初始化一些数据
        products.put(counter.incrementAndGet(), new Product(1L, "Desktop Computer B", 1500.99));
        products.put(counter.incrementAndGet(), new Product(2L, "Wireless Mouse B", 35.50));
        products.put(counter.incrementAndGet(), new Product(3L, "Mechanical Keyboard B", 95.00));
        products.put(counter.incrementAndGet(), new Product(4L, "Monitor B", 299.99));
        products.put(counter.incrementAndGet(), new Product(5L, "Headset B", 129.99));
    }

    // GET: 根据ID获取产品 (专门为断路器B设计)
    @SneakyThrows
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        System.out.println("Provider B: GET /products/" + id + " called" + getInstancePortInfo());
        
        // 针对断路器B的测试场景
        if (id == 999L) {
            // 模拟慢调用，超过2秒阈值 (触发慢调用熔断)
            Thread.sleep(3000);
            System.out.println("Provider B: 模拟慢调用 - 延迟3秒");
        } else if (id == 888L) {
            // 模拟服务异常 (触发失败率熔断)
            System.out.println("Provider B: 模拟服务异常");
            throw new RuntimeException("Provider B: 模拟服务异常");
        } else if (id >= 100L && id < 200L) {
            // 模拟随机慢调用 (40%概率)
            if (Math.random() < 0.4) {
                Thread.sleep(2500);
                System.out.println("Provider B: 随机慢调用 - 延迟2.5秒");
            }
        } else if (id >= 200L && id < 300L) {
            // 模拟随机失败 (60%概率失败，用于测试失败率阈值50%)
            if (Math.random() < 0.6) {
                System.out.println("Provider B: 随机服务失败");
                throw new RuntimeException("Provider B: 随机服务失败");
            }
        }
        
        Product product = products.get(id);
        if (product != null) {
            return ResponseEntity.ok(product);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // PUT: 更新产品 (专门为断路器B设计)
    @SneakyThrows
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
        System.out.println("Provider B: PUT /products/" + id + " called with product: " + productDetails + getInstancePortInfo());
        
        // 模拟慢调用场景
        if (id == 999L) {
            Thread.sleep(3000);
            System.out.println("Provider B: 更新操作慢调用 - 延迟3秒");
        } else if (id == 888L) {
            System.out.println("Provider B: 更新操作失败");
            throw new RuntimeException("Provider B: 更新操作失败");
        }
        
        Product product = products.get(id);
        if (product != null) {
            product.setName(productDetails.getName());
            product.setPrice(productDetails.getPrice());
            products.put(id, product);
            return ResponseEntity.ok(product);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // GET: 获取所有产品 (提供正常服务)
    @GetMapping
    public ResponseEntity<java.util.List<Product>> getAllProducts() {
        System.out.println("Provider B: GET /products called" + getInstancePortInfo());
        return ResponseEntity.ok(products.values().stream().collect(java.util.stream.Collectors.toList()));
    }

    // POST: 创建新产品 (提供正常服务)
    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        long newId = counter.incrementAndGet();
        product.setId(newId);
        products.put(newId, product);
        System.out.println("Provider B: POST /products called with product: " + product + getInstancePortInfo());
        return ResponseEntity.status(HttpStatus.CREATED).body(product);
    }

    // DELETE: 删除产品 (提供正常服务)
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        System.out.println("Provider B: DELETE /products/" + id + " called" + getInstancePortInfo());
        Product removedProduct = products.remove(id);
        if (removedProduct != null) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 健康检查端点
    @GetMapping("/health")
    public ResponseEntity<String> health() {
        return ResponseEntity.ok("Provider B is healthy" + getInstancePortInfo());
    }
} 